package net.alegen.android.pizzashop.order;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class Order {
	
	public static ShapeEnum shape;
	public static CheeseEnum cheese;
	private static List<ToppingEnum> toppings;
	public static String name;
	public static String telephone;
	
	public static void newOrder() {
		shape = ShapeEnum.CIRCLE;
		cheese = CheeseEnum.MEDIUM;
		toppings = new ArrayList<ToppingEnum>();
		toppings.add(ToppingEnum.PEPPERONI);
		toppings.add(ToppingEnum.VEGGIES);
		name = "";
		telephone = "";
	}
	
	public static void addTopping(ToppingEnum topping) {
		boolean isAdded = false;
		for(int i = 0; i < toppings.size(); i++)
			if(toppings.get(i) == topping)
				isAdded = true;
		if(!isAdded)
			toppings.add(topping);
	}
	
	public static void removeTopping(ToppingEnum topping) {
		for(int i = 0; i < toppings.size(); i++)
			if(toppings.get(i) == topping)
				toppings.remove(i);
	}
	
	public static String xml() throws Exception {
		try {
			Element elemCoordinates = new Element("or");
			Document doc = new Document(elemCoordinates);
			
			Element eName = new Element("nm");
			eName.addContent(cheese.toShortString());
			doc.getRootElement().addContent(eName);
			
			Element eTelephone = new Element("ph");
			eTelephone.addContent(cheese.toShortString());
			doc.getRootElement().addContent(eTelephone);
			
			Element eShape = new Element("sh");
			eShape.addContent(shape.toShortString());
			doc.getRootElement().addContent(eShape);
			
			Element eCheese = new Element("ch");
			eCheese.addContent(cheese.toShortString());
			doc.getRootElement().addContent(eCheese);
			
			Element eToppings = new Element("tps");
			for(int i = 0; i < toppings.size(); i++) {
				Element eTopping = new Element("tp");
				eTopping.addContent(toppings.get(i).toShortString());
				eToppings.addContent(eTopping);
			}
			doc.getRootElement().addContent(eToppings);
			
			StringWriter strWriter = new StringWriter();
			XMLOutputter xmlOutput = new XMLOutputter();
			xmlOutput.setFormat(Format.getPrettyFormat());
			xmlOutput.output(doc, strWriter);
			
			return strWriter.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String prettyString() {
		String str = "Shape: " + shape.toString() + "\n" +
				"Cheese: " + cheese.toString() + "\n" +
				"Toppings: ";
		for(int i = 0; i < toppings.size(); i++)
			str += toppings.get(i).toString() + " ";
		return str;
	}
}